package com.hwl.sms.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.hwl.commonutils.exception.GuliException;
import com.hwl.commonutils.result.RespBean;
import com.hwl.commonutils.result.ResultCodeEnum;
import com.hwl.commonutils.utils.HttpUtils;
import com.hwl.commonutils.utils.RandomUtils;
import com.hwl.sms.mapper.MemberMapper;
import com.hwl.sms.service.SmsService;
import com.hwl.sms.util.SmsProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class SmsServiceImpl implements SmsService {

    @Resource
    private RedisTemplate<String, String> redisTemplate;
    @Resource
    private SmsProperties smsProperties;
    @Resource
    private MemberMapper memberMapper;

    @Override
    public RespBean send(String phone) {
        //从redis获取验证码，如果获取到直接返回
        String code = redisTemplate.opsForValue().get(phone);
        if (!StringUtils.isEmpty(code)) {
            return RespBean.error().message("短信已经发送！请稍后再试");
        }

        if (memberMapper.getCountPhone(phone) > 0) {
            throw new GuliException(ResultCodeEnum.REGISTER_MOBLE_ERROR);
        }

        //如果redis获取不到，就生成随机值
        code = RandomUtils.getSixBitRandom();

        String host = "https://gyytz.market.alicloudapi.com";
        String path = "/sms/smsSend";

        String appCode = smsProperties.getAppCode();
        Map<String, String> headers = new HashMap<>();
        headers.put("Authorization", "APPCODE " + appCode);

        Map<String, String> querys = new HashMap<>();
        querys.put("mobile", phone); //手机号
        querys.put("param", "**code**:" + code + ",**minute**:5"); //验证码，有效时间
        querys.put("smsSignId", smsProperties.getSmsSignId()); //签名ID
        querys.put("templateId", smsProperties.getTemplateId()); //模板ID

        Map<String, String> bodys = new HashMap<>();

        try {
            //发送短信
            HttpResponse response = HttpUtils.doPost(host, path, headers, querys, bodys);

            JSONObject json = HttpUtils.getJson(response);
            String res = ((String) json.get("code"));

            if ("1403".equals(res)) {
                return RespBean.error().message("手机号码不正确！");
            } else if ("0".equals(res)) {
                //发送成功，将验证码存入redis中，设置有效时间5分钟
                redisTemplate.opsForValue().set(phone, code, 5, TimeUnit.MINUTES);
                log.info("短信发送成功，验证码为{}", code);
                return RespBean.ok().message("短信发送成功！");
            }
            return RespBean.error().message("短信发送失败！请稍后再试");

        } catch (Exception e) {
            log.error("发生异常，短信发送失败！");
            throw new GuliException(ResultCodeEnum.SMS_SEND_ERROR);
        }
    }

}
